package com.ndood.reconciliation.app.redis;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * https://www.cnblogs.com/linjiqin/p/8003838.html
 */
@Component
public class RedisTool {
	private final Logger debug = LoggerFactory.getLogger("debug");
	
	private final int BATCH_COUNT = 300;
	
	@Autowired
    private JedisPool jedisPool;

	/**
	 * 从snapchat队列获取一个key
	 */
	public Optional<String> spopReconKeyFromSnapchat() {
		Jedis jedis = jedisPool.getResource();
		Optional<String> value = Optional.ofNullable(jedis.spop(RedisReconKeyHelper.KEY_STORE_SNAPCHAT));
		jedis.close();
		return value;
	}

	/**
	 * 获取锁，失效时间为2分钟
	 */
	public boolean getLock(String reconkey) {
		String key = reconkey;
		Jedis jedis = jedisPool.getResource();
		long current = System.currentTimeMillis();
		boolean res = jedis.setnx(key, String.valueOf(current)) == 1;
		if (res) {
			jedis.expire(key, 120);
		} else {
			String lockTs = jedis.get(key);
			if (!StringUtils.isEmpty(lockTs) && current - Long.parseLong(lockTs) > 180000) {
				jedis.set(key, String.valueOf(current));
				jedis.expire(key, 120);
				res = true;
			}
		}
		jedis.close();
		return res;
	}

	/**
	 * 删除锁
	 */
	public void delLock(String reconkey) {
		Jedis jedis = jedisPool.getResource();
		jedis.del(reconkey);
		jedis.close();
	}

	/**
	 * 从队列中获取订单
	 */
	@Deprecated
	public List<String> getOrders(String reconKey) {
		Jedis jedis = jedisPool.getResource();
		List<String> recons = jedis.lrange(reconKey, 0, BATCH_COUNT - 1);
		if (recons != null && recons.size() > 0) {
			jedis.ltrim(reconKey, recons.size(), -1);
		}
		if (recons.size() == BATCH_COUNT) {
			Long leftCount = jedis.llen(reconKey);
			debug.info("getRecon reconKey:{} leftCount:{}", reconKey, leftCount);
		}
		jedis.close();
		return recons;
	}

	/**
	 * 添加到缓存队列
	 */
	public void saddReconKey(String reconKey) {
		Jedis jedis = jedisPool.getResource();
		jedis.sadd(RedisReconKeyHelper.KEY_STORE, reconKey);
		jedis.close();
	}

	/**
	 * 将缓存队列转换成实时队列
	 */
	public void createSnapchat() {
		Jedis jedis = jedisPool.getResource();
		try {
			jedis.renamenx(RedisReconKeyHelper.KEY_STORE, RedisReconKeyHelper.KEY_STORE_SNAPCHAT);
		} catch (Exception ignored) {
		}
		jedis.close();
	}
	
}